/**
 * @desc 封装数据库连接池，并promise化
 */

const mysql = require("mysql")
const { databaseConfig } = require("../configs")

const pool = mysql.createPool(databaseConfig)

function query(sql, values) {
    return new Promise((resolve, reject) => {
        pool.getConnection((err, connection) => {
            if (err) {
                reject({ success: false, err })
            } else {
                connection.query(sql, values, (err, result) => {
                    if (err) {
                        reject({ success: false, err })
                    } else {
                        resolve({ success: true, data: result })
                    }
                })

                connection.release()
            }
        })
    })
}

module.exports = { query }
